﻿using ArienToolkits.Cryptography;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;

namespace ArienToolkits.MVC4.Html
{
    /// <summary>
    /// HtmlHelper扩展类
    /// </summary>
    public static class HtmlExtension
    {
        #region 防重复提交隐藏域
        /// <summary>
        /// 防重复提交隐藏域
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static MvcHtmlString GenerateVerficationToken(this System.Web.Mvc.HtmlHelper helper)
        {
            TagBuilder builder = new TagBuilder("input");
            builder.Attributes.Add("type", "hidden");
            builder.Attributes.Add("name", "");
            builder.Attributes.Add("value", (HttpContext.Current.Session.SessionID + DateTime.Now.Ticks.ToString()).ToMD5());
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
        #endregion

        #region 提交按钮
        /// <summary>
        /// 生成提交按钮
        /// </summary>
        /// <param name="helper">扩展源</param>
        /// <returns></returns>
        public static MvcHtmlString Submit(this System.Web.Mvc.HtmlHelper helper)
        {
            return Submit(helper, "提交");
        }

        /// <summary>
        /// 生成提交按钮
        /// </summary>
        /// <param name="helper">扩展源</param>
        /// <param name="text">显示文本</param>
        /// <returns></returns>
        public static MvcHtmlString Submit(this System.Web.Mvc.HtmlHelper helper, string text)
        {
            return Submit(helper, text, null);
        }

        /// <summary>
        /// 生成提交按钮
        /// </summary>
        /// <param name="helper">扩展源</param>
        /// <param name="text">显示文本</param>
        /// <param name="htmlAttributes">Html标签属性</param>
        /// <returns></returns>
        public static MvcHtmlString Submit(this System.Web.Mvc.HtmlHelper helper, string text, object htmlAttributes)
        {
            TagBuilder builder = new TagBuilder("input");
            builder.Attributes.Add("type", "submit");
            builder.Attributes.Add("value", text);

            //解析并合并属性
            IDictionary<string, object> htmlAttributeDic = ((IDictionary<string, object>)System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
            builder.MergeAttributes<string, object>(htmlAttributeDic);

            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
        #endregion
    }
}
